package com.heart.sell.aspect;

import com.heart.sell.constant.CookConstant;
import com.heart.sell.constant.RedisConstant;
import com.heart.sell.exception.SellAuthorizeException;
import com.heart.sell.exception.SellException;
import com.heart.sell.util.CookieUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * @author Luo Zhen
 */
@Aspect
@Component
@Slf4j
public class SellerAuthorizeAspect {

    @Autowired
    private StringRedisTemplate template;

    @Pointcut("execution(public * com.heart.sell.controller.backend.Seller*.*(..))" +
            "&& !execution(public * com.heart.sell.controller.backend.SellerUserController.*(..))")
    public void verify() {
    }

    @Before("verify()")
    public void doVerify() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        // 查寻cookie
        Cookie cookie = CookieUtil.get(request, CookConstant.TOKEN);
        if (cookie == null) {
            log.error("【登录效验】 Cookie中查不到token");
            throw new SellAuthorizeException();
        }

        // reids查询
        String tokenValue = template.opsForValue().get(String.format(RedisConstant.TOKEN_PREFIX + cookie.getValue()));
        if (StringUtils.isEmpty(tokenValue)) {
            log.error("【登录效验】查不到token");
            throw new SellAuthorizeException();
        }

    }
}
